<script setup lang="ts">
//
import CustomNavbar from '@/pages/index/components/CustomNavbar.vue'
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerApi, getHomeCategoryApi, getHomeHotApi } from '@/services/home'
import CategoryPanel from '@/pages/index/components/CategoryPanel.vue'
import HotPanel from '@/pages/index/components/HotPanel.vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import XtxGuess from '@/components/XtxGuess.vue'
import type { XtxGuessInstance } from '@/types/component'
import PageSkeleton from '@/pages/index/components/PageSkeleton.vue'
import { useGuessList } from '@/composables'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryApi()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotApi()
  hotList.value = res.result
}

const { guessRef, onScrolltolower } = useGuessList()
// const guessRef = ref<XtxGuessInstance>()
// const onScrolltolower = () => {
//   // 调用子组件方法
//   guessRef.value?.getMore()
// }
// 是否正在加载
const isLoading = ref(false)

// 在页面加载的时候调用，看uni的生命周期
onLoad(() => {
  isLoading.value = true
  // getHomeBannerData()
  // getHomeCategoryData()
  // getHomeHotData()
  Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

// refresher-enabled:开启自定义下拉刷新    默认值：false

// 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
const isTriggered = ref(false)

// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  isTriggered.value = true

  // 重置猜你喜欢的参数
  guessRef.value?.resetData()

  // 这样需要一个一个方法的执行，体验不好
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  // await guessRef.value?.getMore()

  // 改为如下，等最长的结束，就结束了
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])

  isTriggered.value = false
}
</script>

<template>
  <!--  首页-->
  <CustomNavbar />
  <scroll-view
    @scrolltolower="onScrolltolower"
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    refresher-enabled
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!--  轮播图-->
      <XtxSwiper :list="bannerList" />
      <!--  首页分类-->
      <CategoryPanel :list="categoryList" />
      <!--  首页-热门推荐-->
      <HotPanel :list="hotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background: #f7f7f7;
  // 父容器高度
  height: 100%;
  //流式布局
  display: flex;
  //布局方向设置
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
